package net.golfklubi.sive;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.List;

import com.thoughtworks.xstream.XStream;

public class CompetitionPersisterAndLoader implements Serializable {

    public CompetitionPersisterAndLoader() {
    }

    public String toXml(final List<Competition> competitions) {
        final String xml = getXStream().toXML(competitions);
        return xml;
    }

    public void saveToFile(final List<Competition> competitions, final String filename) throws IOException {
        final OutputStream output = newFileOutputStream(filename);
        output.write(toXml(competitions).getBytes());
        output.close();
    }

    protected OutputStream newFileOutputStream(final String filename) throws FileNotFoundException {
        return new FileOutputStream(new File(filename));
    }

    public List<Competition> loadFromFile(final String filename) {
        return loadCompetitions(filename);
    }

    @SuppressWarnings("unchecked")
    private List<Competition> loadCompetitions(final String filename) {
        try {
            final File file = new File(filename);
            final List<Competition> competitionsAndGuesses;
            if (!file.exists()) {
                competitionsAndGuesses = loadCompetitions();
            } else {
                final FileInputStream input = new FileInputStream(file);
                competitionsAndGuesses = (List<Competition>) getXStream().fromXML(input);
            }
            return competitionsAndGuesses;
        } catch (final FileNotFoundException e) {
            // return empty wishList
        }
        return java.util.Collections.emptyList();
    }

    protected XStream getXStream() {
        return XStreamFactory.getObjectInstance();
    }

    @SuppressWarnings("unchecked")
    private List<Competition> loadCompetitions() throws FileNotFoundException {
        return (List<Competition>) getXStream().fromXML(new FileInputStream(new File("competitions.xml")));

    }

}
